<template>
  <div class="history-manager">
    <!-- 历史记录面板 -->
    <el-drawer
      v-model="visible"
      title="历史记录"
      direction="rtl"
      size="450px"
      :before-close="handleClose"
    >
      <div class="history-content">
        <!-- 工具栏 -->
        <div class="toolbar">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="timeline">时间轴</el-radio-button>
            <el-radio-button label="version">版本</el-radio-button>
          </el-radio-group>
          
          <el-button-group size="small">
            <el-button @click="exportHistory">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button @click="clearHistory">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </el-button-group>
        </div>

        <!-- 时间轴视图 -->
        <div v-if="viewMode === 'timeline'" class="timeline-view">
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in historyRecords"
              :key="index"
              :timestamp="formatTimestamp(record.timestamp)"
              :type="getRecordType(record.type)"
              placement="top"
            >
              <el-card class="history-card" shadow="hover">
                <div class="history-header">
                  <div class="history-type">
                    <el-icon>
                      <component :is="getRecordIcon(record.type)" />
                    </el-icon>
                    <span>{{ record.title }}</span>
                  </div>
                  <el-tag :type="getRecordTagType(record.type)" size="small">
                    {{ record.type }}
                  </el-tag>
                </div>
                
                <div class="history-desc">{{ record.description }}</div>
                
                <div v-if="record.changes" class="history-changes">
                  <div class="change-title">变更内容：</div>
                  <div
                    v-for="(change, idx) in record.changes"
                    :key="idx"
                    class="change-item"
                  >
                    <span class="change-field">{{ change.field }}</span>
                    <span class="change-arrow">→</span>
                    <span class="change-value">{{ change.newValue }}</span>
                  </div>
                </div>
                
                <div class="history-actions">
                  <el-button-group size="small">
                    <el-button @click="restoreHistory(record)">
                      <el-icon><RefreshLeft /></el-icon>
                      恢复
                    </el-button>
                    <el-button @click="compareHistory(record)">
                      <el-icon><DocumentCopy /></el-icon>
                      对比
                    </el-button>
                    <el-button @click="viewDetails(record)">
                      <el-icon><View /></el-icon>
                      详情
                    </el-button>
                  </el-button-group>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          
          <el-empty
            v-if="historyRecords.length === 0"
            description="暂无历史记录"
            :image-size="100"
          />
        </div>

        <!-- 版本视图 -->
        <div v-if="viewMode === 'version'" class="version-view">
          <div class="version-list">
            <div
              v-for="(version, index) in versions"
              :key="index"
              class="version-item"
              :class="{ active: version.isCurrent }"
              @click="selectVersion(version)"
            >
              <div class="version-header">
                <div class="version-number">
                  <el-icon><Collection /></el-icon>
                  {{ version.name }}
                </div>
                <el-tag v-if="version.isCurrent" type="success" size="small">
                  当前版本
                </el-tag>
              </div>
              
              <div class="version-info">
                <div class="version-desc">{{ version.description }}</div>
                <div class="version-meta">
                  <span>{{ version.author }}</span>
                  <span>{{ formatTimestamp(version.timestamp) }}</span>
                </div>
              </div>
              
              <div class="version-actions">
                <el-button-group size="small">
                  <el-button
                    v-if="!version.isCurrent"
                    type="primary"
                    @click.stop="restoreVersion(version)"
                  >
                    <el-icon><RefreshLeft /></el-icon>
                    恢复此版本
                  </el-button>
                  <el-button @click.stop="downloadVersion(version)">
                    <el-icon><Download /></el-icon>
                    下载
                  </el-button>
                  <el-button
                    v-if="!version.isCurrent"
                    type="danger"
                    @click.stop="deleteVersion(version)"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
          
          <!-- 创建版本 -->
          <div class="create-version">
            <el-button type="primary" @click="showCreateVersion = true" style="width: 100%">
              <el-icon><Plus /></el-icon>
              创建新版本
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 创建版本对话框 -->
    <el-dialog
      v-model="showCreateVersion"
      title="创建新版本"
      width="500px"
    >
      <el-form :model="versionForm" label-width="100px">
        <el-form-item label="版本名称" required>
          <el-input v-model="versionForm.name" placeholder="如：v1.0.0" />
        </el-form-item>
        <el-form-item label="版本说明" required>
          <el-input
            v-model="versionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请描述本次版本的主要变更..."
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="versionForm.tags"
            multiple
            placeholder="选择标签"
            style="width: 100%"
          >
            <el-option label="功能更新" value="feature" />
            <el-option label="Bug修复" value="bugfix" />
            <el-option label="性能优化" value="performance" />
            <el-option label="样式调整" value="style" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateVersion = false">取消</el-button>
        <el-button type="primary" @click="createVersion">创建</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetails"
      title="历史详情"
      width="700px"
    >
      <div v-if="currentRecord" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作类型">
            {{ currentRecord.type }}
          </el-descriptions-item>
          <el-descriptions-item label="操作时间">
            {{ formatTimestamp(currentRecord.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="操作标题" :span="2">
            {{ currentRecord.title }}
          </el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">
            {{ currentRecord.description }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentRecord.snapshot" class="snapshot-section">
          <h4>快照数据</h4>
          <el-input
            v-model="currentRecord.snapshot"
            type="textarea"
            :rows="10"
            readonly
          />
        </div>
      </div>
    </el-dialog>

    <!-- 对比对话框 -->
    <el-dialog
      v-model="showCompare"
      title="版本对比"
      width="900px"
    >
      <div class="compare-view">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="compare-panel">
              <div class="compare-header">原版本</div>
              <div class="compare-content">
                <!-- 这里可以显示原版本内容 -->
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="compare-panel">
              <div class="compare-header">新版本</div>
              <div class="compare-content">
                <!-- 这里可以显示新版本内容 -->
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Download,
  Delete,
  RefreshLeft,
  DocumentCopy,
  View,
  Collection,
  Plus,
  Edit,
  Document,
  Connection,
  Setting
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  recordKey: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'restore'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const viewMode = ref('timeline')
const historyRecords = ref([])
const versions = ref([])
const showCreateVersion = ref(false)
const showDetails = ref(false)
const showCompare = ref(false)
const currentRecord = ref(null)

const versionForm = ref({
  name: '',
  description: '',
  tags: []
})

// 获取记录图标
const getRecordIcon = (type) => {
  const icons = {
    '创建': 'Plus',
    '编辑': 'Edit',
    '删除': 'Delete',
    '保存': 'Document',
    '发布': 'Promotion'
  }
  return icons[type] || 'Document'
}

// 获取记录类型
const getRecordType = (type) => {
  const types = {
    '创建': 'success',
    '编辑': 'primary',
    '删除': 'danger',
    '保存': 'info',
    '发布': 'warning'
  }
  return types[type] || 'info'
}

// 获取标签类型
const getRecordTagType = (type) => {
  const types = {
    '创建': 'success',
    '编辑': '',
    '删除': 'danger',
    '保存': 'info',
    '发布': 'warning'
  }
  return types[type] || ''
}

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  // 今天
  if (diff < 86400000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 昨天
  if (diff < 172800000 && date.getDate() === now.getDate() - 1) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 其他
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载历史记录
const loadHistory = () => {
  const saved = localStorage.getItem(`history_${props.recordKey}`)
  if (saved) {
    try {
      historyRecords.value = JSON.parse(saved)
    } catch (e) {
      console.error('Failed to load history:', e)
    }
  }
}

// 加载版本
const loadVersions = () => {
  const saved = localStorage.getItem(`versions_${props.recordKey}`)
  if (saved) {
    try {
      versions.value = JSON.parse(saved)
    } catch (e) {
      console.error('Failed to load versions:', e)
    }
  }
}

// 保存历史记录
const saveHistory = () => {
  localStorage.setItem(`history_${props.recordKey}`, JSON.stringify(historyRecords.value))
}

// 保存版本
const saveVersions = () => {
  localStorage.setItem(`versions_${props.recordKey}`, JSON.stringify(versions.value))
}

// 添加历史记录
const addHistory = (record) => {
  historyRecords.value.unshift({
    ...record,
    timestamp: new Date().getTime()
  })
  
  // 最多保留100条
  if (historyRecords.value.length > 100) {
    historyRecords.value = historyRecords.value.slice(0, 100)
  }
  
  saveHistory()
}

// 恢复历史
const restoreHistory = (record) => {
  ElMessageBox.confirm(
    `确定要恢复到"${record.title}"这个状态吗？`,
    '恢复历史',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    emit('restore', record)
    ElMessage.success('已恢复到历史版本')
  })
}

// 对比历史
const compareHistory = (record) => {
  currentRecord.value = record
  showCompare.value = true
}

// 查看详情
const viewDetails = (record) => {
  currentRecord.value = record
  showDetails.value = true
}

// 导出历史
const exportHistory = () => {
  const data = JSON.stringify(historyRecords.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `history_${props.recordKey}_${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('历史记录已导出')
}

// 清空历史
const clearHistory = () => {
  ElMessageBox.confirm('确定要清空所有历史记录吗？', '清空历史', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    historyRecords.value = []
    saveHistory()
    ElMessage.success('历史记录已清空')
  })
}

// 选择版本
const selectVersion = (version) => {
  currentRecord.value = version
}

// 恢复版本
const restoreVersion = (version) => {
  ElMessageBox.confirm(
    `确定要恢复到版本"${version.name}"吗？`,
    '恢复版本',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 更新当前版本标记
    versions.value.forEach(v => {
      v.isCurrent = v === version
    })
    saveVersions()
    emit('restore', version)
    ElMessage.success('已恢复到指定版本')
  })
}

// 下载版本
const downloadVersion = (version) => {
  const data = JSON.stringify(version, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${version.name}_${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('版本已下载')
}

// 删除版本
const deleteVersion = (version) => {
  ElMessageBox.confirm(
    `确定要删除版本"${version.name}"吗？`,
    '删除版本',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = versions.value.indexOf(version)
    if (index > -1) {
      versions.value.splice(index, 1)
      saveVersions()
      ElMessage.success('版本已删除')
    }
  })
}

// 创建版本
const createVersion = () => {
  if (!versionForm.value.name || !versionForm.value.description) {
    ElMessage.warning('请填写版本名称和说明')
    return
  }
  
  // 取消之前的当前版本标记
  versions.value.forEach(v => {
    v.isCurrent = false
  })
  
  const newVersion = {
    name: versionForm.value.name,
    description: versionForm.value.description,
    tags: versionForm.value.tags,
    author: '当前用户',
    timestamp: new Date().getTime(),
    isCurrent: true
  }
  
  versions.value.unshift(newVersion)
  saveVersions()
  
  showCreateVersion.value = false
  versionForm.value = { name: '', description: '', tags: [] }
  ElMessage.success('版本创建成功')
}

// 关闭
const handleClose = () => {
  visible.value = false
}

// 监听显示状态
watch(visible, (val) => {
  if (val) {
    loadHistory()
    loadVersions()
  }
})

// 暴露方法
defineExpose({
  addHistory
})
</script>

<style scoped>
.history-manager {
  /* 容器样式 */
}

.history-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

/* 时间轴视图 */
.timeline-view {
  flex: 1;
  overflow-y: auto;
}

.history-card {
  margin-bottom: 12px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-type {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.history-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 12px;
}

.history-changes {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 12px;
}

.change-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.change-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  margin-bottom: 4px;
}

.change-field {
  color: #606266;
}

.change-arrow {
  color: #909399;
}

.change-value {
  color: #409eff;
  font-weight: 500;
}

.history-actions {
  display: flex;
  justify-content: flex-end;
}

/* 版本视图 */
.version-view {
  flex: 1;
  overflow-y: auto;
}

.version-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.version-item {
  padding: 16px;
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.version-item:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.version-item.active {
  border-color: #67c23a;
  background: #f0f9ff;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.version-number {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.version-info {
  margin-bottom: 12px;
}

.version-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.version-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #909399;
}

.version-actions {
  display: flex;
  justify-content: flex-end;
}

.create-version {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 详情 */
.detail-content {
  padding: 20px 0;
}

.snapshot-section {
  margin-top: 20px;
}

.snapshot-section h4 {
  margin-bottom: 12px;
  color: #303133;
}

/* 对比视图 */
.compare-view {
  padding: 20px 0;
}

.compare-panel {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.compare-header {
  background: #f5f7fa;
  padding: 12px 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 1px solid #f0f0f0;
}

.compare-content {
  padding: 16px;
  min-height: 400px;
}

/* 滚动条 */
.timeline-view::-webkit-scrollbar,
.version-view::-webkit-scrollbar {
  width: 6px;
}

.timeline-view::-webkit-scrollbar-thumb,
.version-view::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}
</style>

